package com.rui.study.algorithm.P_单链表合并两个有序链表;


import com.rui.study.algorithm.ListNode;

public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = null;
        ListNode p = null;

        while (l1 != null || l2 != null) {
            if (l2 == null || (l1 != null && l1.val < l2.val)) {
                if (head == null) {
                    head = l1;
                    p = head;
                } else {
                    p.next = l1;
                    p = p.next;
                }
                l1 = l1.next;
            } else {
                if (head == null) {
                    head = l2;
                    p = head;
                } else {
                    p.next = l2;
                    p = p.next;
                }
                l2 = l2.next;
            }
        }

        return head;
    }

    public static void main(String[] args) {
        ListNode node1_1 = new ListNode(1);
        ListNode node1_2 = new ListNode(3);
        ListNode node1_3 = new ListNode(5);
        ListNode node1_4 = new ListNode(7);
        node1_1.next = node1_2;
        node1_2.next = node1_3;
        node1_3.next = node1_4;

        ListNode node2_1 = new ListNode(0);
        ListNode node2_2 = new ListNode(4);
        ListNode node2_3 = new ListNode(6);
        ListNode node2_4 = new ListNode(8);
        node2_1.next = node2_2;
        node2_2.next = node2_3;
        node2_3.next = node2_4;


        System.out.println("l1: " + print(node1_1));
        System.out.println("l2: " + print(node2_1));

        Solution solution = new Solution();
        System.out.println("merged: " + print(solution.mergeTwoLists(node1_1, node2_1)));

    }

    public static String print(ListNode head) {
        if (head == null) {
            return "";
        }
        String nextVal = print(head.next);
        if (nextVal.length() > 0) {
            nextVal = "->" + nextVal;
        }
        return head.val + nextVal;
    }
}
